﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using Yu.Cms.Common;
using System.Drawing;
namespace Yu.Cms.Web.Admin
{
    public partial class doUpload : System.Web.UI.Page
    {
        private string NoFileMessage = "您没有选择文件。";
        private string UploadSuccessMessage = "上传成功";
        //private string UploadFailureMessage = "上传失败。";
        private string InvalidFileTypeMessage = "只允许上传 jpg, jpeg, jpe, gif, png,bmp 类型的文件";
        private string[] AcceptedFileTypes = new string[] { "jpg", "jpeg", "jpe", "gif", "png","bmp" };

        protected void Page_Load(object sender, EventArgs e)
        {            
            string sfilePath = Utils.GetRootPath() + ConfigHelper.GetConfigString("PhotoPath"); //文件路径            
            if (Request.Files.Count > 0)
            {
                this.UpLoadImage(sfilePath, "thumb_", 118, 118);
            }           
        }



        /// <summary>
        /// 判断文件类型
        /// </summary>
        /// <param name="FileName"></param>
        /// <returns></returns>
        private bool IsValidFileType(string FileName)
        {
            string ext = FileName.Substring(FileName.LastIndexOf(".") + 1, FileName.Length - FileName.LastIndexOf(".") - 1);
            for (int i = 0; i < AcceptedFileTypes.Length; i++)
            {
                if (ext.ToLower() == AcceptedFileTypes[i])
                {
                    return true;
                }
            }
            return false;
        }


        /// <summary> 
        /// asp.net上传图片并生成缩略图 
        /// </summary>       
        /// <param name="sSavePath">保存的路径,些为相对服务器路径的下的文件夹</param> 
        /// <param name="sThumbExtension">缩略图的thumb</param> 
        /// <param name="intThumbWidth">生成缩略图的宽度</param> 
        /// <param name="intThumbHeight">生成缩略图的高度</param> 
        /// <returns>缩略图名称</returns> 
        public void UpLoadImage(string sSavePath, string sThumbExtension, int intThumbWidth, int intThumbHeight)
        {
            string error = "";
            string sThumbFile = "";
            string sFilename = "";
            string msg = "";
            string result = "";
            HttpPostedFile myFile = Request.Files[0];     //上传文件  
            int nFileLen = myFile.ContentLength;  //文件大小
            if (nFileLen == 0)
            {
                error = NoFileMessage;
            }
            if (!IsValidFileType(myFile.FileName))
            {
                error = InvalidFileTypeMessage;
            }

            byte[] myData = new Byte[nFileLen];
            myFile.InputStream.Read(myData, 0, nFileLen);

            sFilename = System.IO.Path.GetFileName(myFile.FileName);          
            //重命名文件名
            string fileName = Utils.sRndNum(5) + System.IO.Path.GetExtension(myFile.FileName);          
            System.IO.FileStream newFile
                = new System.IO.FileStream(sSavePath + fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            newFile.Write(myData, 0, myData.Length);
            newFile.Close();

            //保存图片名称和路径
            Utils.WriteCookie("fileName", fileName, 10);
            Utils.WriteCookie("filePath", ConfigHelper.GetConfigString("PhotoPath") + fileName, 10);

            //以上为上传原图 

            try
            {
                //原图加载 
                using (System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(sSavePath + fileName))
                {
                    //原图宽度和高度 
                    int width = sourceImage.Width;
                    int height = sourceImage.Height;
                    int smallWidth;
                    int smallHeight;

                    //获取第一张绘制图的大小,(比较 原图的宽/缩略图的宽  和 原图的高/缩略图的高) 
                    if (((decimal)width) / height <= ((decimal)intThumbWidth) / intThumbHeight)
                    {
                        smallWidth = intThumbWidth;
                        smallHeight = intThumbWidth * height / width;
                    }
                    else
                    {
                        smallWidth = intThumbHeight * width / height;
                        smallHeight = intThumbHeight;
                    }
                    
                    //缩略图文件名
                    sThumbFile = sThumbExtension + fileName;
                   
                    //缩略图保存的绝对路径 
                    string smallImagePath = sSavePath + sThumbFile;

                    //新建一个图板,以最小等比例压缩大小绘制原图 
                    using (System.Drawing.Image bitmap = new System.Drawing.Bitmap(smallWidth, smallHeight))
                    {
                        //绘制中间图 
                        using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
                        {
                            //高清,平滑 
                            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                            g.Clear(Color.Black);
                            g.DrawImage(
                            sourceImage,
                            new System.Drawing.Rectangle(0, 0, smallWidth, smallHeight),
                            new System.Drawing.Rectangle(0, 0, width, height),
                            System.Drawing.GraphicsUnit.Pixel
                            );
                        }
                        //新建一个图板,以缩略图大小绘制中间图 
                        using (System.Drawing.Image bitmap1 = new System.Drawing.Bitmap(intThumbWidth, intThumbHeight))
                        {
                            //绘制缩略图 
                            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap1))
                            {
                                //高清,平滑 
                                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                                g.Clear(Color.Black);
                                int lwidth = (smallWidth - intThumbWidth) / 2;
                                int bheight = (smallHeight - intThumbHeight) / 2;
                                g.DrawImage(bitmap, new Rectangle(0, 0, intThumbWidth, intThumbHeight), lwidth, bheight, intThumbWidth, intThumbHeight, GraphicsUnit.Pixel);
                                g.Dispose();
                                bitmap1.Save(smallImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                            }
                        }
                        Utils.WriteCookie("thumbPath", ConfigHelper.GetConfigString("PhotoPath") + sThumbFile, 10);
                        msg = UploadSuccessMessage;
                    }
                }
               
            }
            catch
            {
                //出错则删除 
                System.IO.File.Delete(sSavePath + fileName);
                error = InvalidFileTypeMessage;
            }
            //返回缩略图名称 
            //return sThumbFile;

            result = "{ error:'" + error + "', msg:'" + msg + "'}";
            if (!string.IsNullOrEmpty(result))
            {
                Response.Write(result);
            }
            Response.End();
        }



    }
}
